package cn.base.web.auth.uri;

import cn.rengy.auth.pathtree.UriPath;
import cn.rengy.auth.pathtree.UriTree;
import cn.rengy.isql.DbService;
import cn.rengy.util.web.RequestUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
@ConditionalOnProperty(name = "enable.cn.base.web.auth.uri.UriAccessControl", havingValue = "true",matchIfMissing=true)
//@ConditionalOnMissingClass("reactor.core.publisher.Mono")//不生效 web项目也会引入Mono
//@ConditionalOnClass(javax.servlet.http.HttpServletRequest.class)
@DS("admin")
public class InitResourceUri {
	@Autowired(required = false)
	private DbService dbService;


	private Date lastUpdateTime;


    @EventListener(ApplicationReadyEvent.class)
    public void handleApplicationReadyEvent(ApplicationReadyEvent event) {
        init();
    }

	/**
	 * 也可以使用 implements  InitializingBean
	 */
	//@PostConstruct
	public void init(){
		if(dbService==null){
			return;
		}
		this.lastUpdateTime=this.dbService.querySingleColumn("select_resource_uri_max_last_modified",Date.class);
		log.info("resource_uri_max_last_modified：{}", DateFormat.getDateTimeInstance().format(lastUpdateTime));
		List<SysResourceUriDTO> all=this.dbService.queryForBeanList(RequestUtil.getString("initResourceSql"),SysResourceUriDTO.class);
		List<UriPath> list=new ArrayList<UriPath>(all.size());
		for(SysResourceUriDTO sysResourceUriDTO:all){
			UriPath uriPath=new UriPath();
			uriPath.setUri(sysResourceUriDTO.getUri());
			uriPath.setMethod(sysResourceUriDTO.getMethod());
			uriPath.setAuthType(sysResourceUriDTO.getAuthType());
			String roles=sysResourceUriDTO.getRoles();
			if(StringUtils.isNotBlank(roles)){
				String[] roless = roles.substring(1, roles.length()-1).split(",");
				uriPath.setRoles(Stream.of(roless).collect(Collectors.toList()));
			}
			list.add(uriPath);
		}
		UriTree.build(list);
	}


	//每分钟执行
	@Scheduled(cron="0 0/1 * * * ?")
	public void check(){
		if(dbService==null){
			return;
		}
		log.info("check resource_uri last_modified");
		Date newUpdateTime=this.dbService.querySingleColumn("select_resource_uri_max_last_modified",Date.class);
		if(!newUpdateTime.equals(lastUpdateTime)){
			init();
		}
	}

}
